<template>
  <div class="app-container">
    <!-- 当月销售情况横幅 -->
    <div class="sales-banner">
      <h1>当月销售情况</h1>
      <p>总销售额: <span class="highlight">￥{{ totalSales }}</span></p>
      <p>总订单数: <span class="highlight">{{ totalOrders }}</span></p>
      <p>热门产品: <span class="highlight">{{ topProduct }}</span></p>
    </div>

    <!-- 图表容器 -->
    <div class="charts-container" style="display: flex; justify-content: space-between; align-items: flex-start; width: 100%; margin-top: 20px;">
      <!-- 左边的图表容器 -->
      <div ref="leftChart" style="width: 49%; height: 400px;"></div>
      <!-- 右边的热门外卖食品小页面 -->
      <div class="hot-products" style="width: 49%; height: 400px; display: flex; flex-direction: column;">
        <!-- 热门外卖食品标题 -->
        <h2 style="text-align: center; margin-bottom: 20px;">热门外卖食品</h2>
        <!-- 表格内容 -->
        <div class="table-container" style="flex: 1; overflow-y: auto;">
          <table>
            <thead>
              <tr>
                <th>名称</th>
                <th>价格</th> <!-- 修改为价格 -->
                <th>销量</th>
              </tr>
            </thead>
            <tbody>
              <tr v-for="(product, index) in hotProducts" :key="index">
                <td>{{ product.name }}</td>
                <td :style="{ color: heatColors[index] }">{{ product.price }}</td> <!-- 显示价格 -->
                <td :style="{ color: salesColors[index] }">{{ product.sales }}</td>
              </tr>
            </tbody>
          </table>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import * as echarts from 'echarts';
import { listDetail } from '@/api/manage/detail'; // 导入封装的请求方法
import { getDish } from '@/api/manage/dish'; // 导入根据 dishId 获取 dish 信息的方法

export default {
  name: 'EChartsExample',
  data() {
    return {
      hotProducts: [], // 热门产品数据
      heatColors: ['#d48265', '#91c7ae', '#749f83', '#ca8622', '#61a0a8', '#c23531', '#2f4554', '#d48265'], // 热度列的颜色
      salesColors: ['#61a0a8', '#c23531', '#2f4554', '#d48265', '#91c7ae', '#749f83', '#ca8622', '#61a0a8'], // 销量列的颜色
      totalSales: 0, // 总销售额
      totalOrders: 0, // 总订单数
      topProduct: '', // 热门产品
    };
  },
  mounted() {
    // 调用 API 获取订单详情数据
    this.fetchOrderDetails();
  },
  methods: {
    async fetchOrderDetails() {
      try {
        // 调用封装的请求方法
        const response = await listDetail();

        const data = response.rows; // 获取 rows 数据

        // 统计每个产品的销量和总金额
        const productMap = {};
        const dishPromises = []; // 存储所有 dishId 的请求
       
        

        data.forEach(item => {
          if (productMap[item.dishId]) {
            productMap[item.dishId].sales += item.number;
            productMap[item.dishId].totalAmount += item.amount;
          } else {
            productMap[item.dishId] = {
              dishId: item.dishId,
              name: item.name,
              sales: item.number,
              totalAmount: item.amount,
            };
          }
           
          // 将 dishId 存入数组，用于后续查询价格
          if (!dishPromises.includes(item.dishId)) {
            dishPromises.push(getDish(item.dishId));
          }
        });

        // 获取所有 dish 的价格
        const dishResponses = await Promise.all(dishPromises);
        const dishPriceMap = {};

        dishResponses.forEach(dish => {
          dishPriceMap[dish.data.id] = dish.data.price;
        });

        // 将产品数据转换为数组并按销量排序
        const products = Object.values(productMap).map(item => ({
          ...item,
          price: dishPriceMap[item.dishId] || '未知价格', // 使用从 store_dish 表中获取的价格
        })).sort((a, b) => b.sales - a.sales);

        // 更新热门产品数据
        this.hotProducts = products.map(item => ({
          name: item.name,
          sales: item.sales,
          price: item.price, // 使用 price 字段
        }));

        // 计算总销售额和总订单数
        this.totalSales = products.reduce((sum, item) => sum + item.totalAmount, 0);
        this.totalOrders = products.reduce((sum, item) => sum + item.sales, 0);

        // 获取热门产品
        this.topProduct = this.hotProducts[0]?.name || '无';

        // 初始化图表
        this.initLeftChart();
      } catch (error) {
        console.error('获取订单详情数据失败：', error);
      }
    },
    initLeftChart() {
      // 基于准备好的dom，初始化echarts实例
      const chartDom = this.$refs.leftChart;
      const myChart = echarts.init(chartDom);

      // 获取数据的最大值
      const maxSales = Math.max(...this.hotProducts.map(product => product.sales));

      // 绘制图表
      myChart.setOption({
        title: {
          text: '热门外卖食品',
          left: 'center',
          textStyle: {
            fontSize: 15,
            color: '#333'
          }
        },
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'shadow'
          }
        },
        legend: {
          data: ['销量'],
          left: 'right'
        },
        xAxis: {
          data: this.hotProducts.map(product => product.name),
          axisLabel: {
            rotate: 30, // X轴标签旋转，避免重叠
            interval: 0, // 强制显示所有标签
          }
        },
        yAxis: {
          type: 'value',
          min: 0, // 设置 Y 轴从 0 开始
          max: maxSales, // 设置 Y 轴的最大值为数据中的最大销量值
          interval: Math.ceil(maxSales / 5), // 设置 Y 轴的刻度间隔
          axisLabel: {
            formatter: function (value) {
              return Math.round(value); // 确保 Y 轴显示整数
            }
          },
          splitNumber: 5, // 控制 Y 轴的分割段数
        },
        series: [
          {
            name: '销量',
            type: 'bar',
            data: this.hotProducts.map(product => product.sales),
            itemStyle: {
              color: '#61a0a8',
              barBorderRadius: [5, 5, 0, 0]
            }
          }
        ]
      });
    }
  }
};
</script>

<style scoped>
/* 添加样式以调整图表的位置 */
.app-container {
  display: flex;
  justify-content: center;
  flex-direction: column;
  align-items: center;
}

.sales-banner {
  width: 100%;
  background-color: palevioletred; /* 绿色背景 */
  color: white;
  padding: 10px 20px; /* 减小横幅高度 */
  text-align: center;
  border-radius: 8px;
  margin-bottom: 20px;
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
}

.sales-banner h1 {
  font-size: 20px; /* 减小标题字体大小 */
  margin-bottom: 5px;
}

.sales-banner p {
  font-size: 16px; /* 减小文本字体大小 */
  margin: 3px 0;
}

.highlight {
  font-weight: bold;
  color: #ffeb3b; /* 黄色高亮 */
}

.charts-container {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  width: 100%;
  margin-top: 20px;
}

.hot-products {
  width: 49%; /* 确保两个图表并排显示 */
  border: 1px solid #ccc;
  padding: 20px;
  background-color: #f9f9f9;
  border-radius: 8px;
  display: flex;
  flex-direction: column;
}

.hot-products h2 {
  text-align: center;
  margin-bottom: 20px;
  color: #333;
}

.table-container {
  flex: 1;
  overflow-y: auto;
}

.hot-products table {
  width: 100%;
  border-collapse: collapse;
}

.hot-products th, .hot-products td {
  padding: 10px;
  text-align: left;
  border-bottom: 1px solid #ddd;
}

.hot-products th {
  background-color: #f2f2f2;
}
</style>